<?php

namespace App\Notifications\Reservation;

use App\Models\Reservation\Reservation;
use App\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class CancelReservationToNurse extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * @var \App\Models\Reservation\Reservation | \Illuminate\Database\Eloquent\Collection
     */
    protected $reservation;

    /**
     * @var \App\User
     */
    protected $user;

    public function __construct($reservation, User $user)
    {
        $this->reservation = $reservation;
        $this->user        = $user;
    }

    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     * @param  User $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return $this->multipleMessage();
    }

    protected function multipleMessage()
    {
        $data['type']    = 'multiple_cancel_reservation';
        $data['source']  = '系统消息';
        $data['count']   = $this->reservation->count();
        $data['message'] = sprintf(
            '%s取消了 %d位患者的预约，请您到患者池进行分配。',
            $this->user->name,
            $this->reservation->count()
        );

        $detail         = $this->reservation->map(function (Reservation $reservation) {
            return $this->format($reservation);
        });
        $data['detail'] = $detail->toArray();

        return $data;
    }

    protected function format(Reservation $reservation)
    {
        $time = Carbon::parse($reservation->time)->startOfDay();

        return [
            'id'           => $reservation->id,   //  预约ID
            'patient_id'   => $reservation->patient_id,
            'patient_name' => $reservation->patient->name,
            'time'         => $reservation->time .
                ' ' . $time->hour($reservation->start)->format('H:i') .
                '-' . $time->hour($reservation->end)->format('H:i'),
            'am'           => $reservation->am ? '上午' : '下午',
            'room'         => $reservation->room,
        ];
    }
}
